package com.shareppy.nomrnaui.list.adapters;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class EntityAdapter extends ArrayAdapter<JSONObject> {

	private JSONArray array;
	private int resourceId;
	private SparseArray<String> mapping;
	private EntityAdapaterItemProcessor processor;

	public EntityAdapter(Context ctx, int resourceId, JSONArray array,
			SparseArray<String> mapping) {
		this(ctx, resourceId, array, mapping, new EntityAdapaterItemProcessor());
	}

	public EntityAdapter(Context ctx, int resourceId, JSONArray array,
			SparseArray<String> mapping, EntityAdapaterItemProcessor processor) {
		super(ctx, resourceId);
		this.array = array;
		this.resourceId = resourceId;
		this.mapping = mapping;
		this.processor = processor;
	}

	@Override
	public int getCount() {
		return array.length();
	}

	@Override
	public JSONObject getItem(int index) {
		try {
			return (JSONObject) array.get(index);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public long getItemId(int index) {
		return index;
	}

	@Override
	public View getView(int index, View view, ViewGroup parent) {
		View v = View.inflate(getContext(), resourceId, null);
		JSONObject item = getItem(index);
		for (int i = 0; i < mapping.size(); i++) {
			int viewId = mapping.keyAt(i);
			String property = mapping.get(viewId);
			View viewItem = v.findViewById(viewId);
			if (viewItem instanceof TextView) {
				TextView tv = (TextView) viewItem;
				try {
					tv.setText(Html.fromHtml((String) processor.process(
							item.optString(property), property, viewId)));
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (viewItem instanceof ImageView) {
				ImageView tv = (ImageView) viewItem;
				try {
					tv.setImageDrawable((Drawable) processor.process(
							item.optString(property), property, viewId));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return v;
	}

	public void update(JSONArray array) {
		this.array = array;
		notifyDataSetChanged();
	}
}